<template>
    <el-button type="primary" icon="download" :disabled="props.disabled" @click="exportExcel">导出</el-button>
</template>

<script>
import { reactive, toRefs } from 'vue'
import * as XLSX from 'xlsx' // Vue3 版本
export default {
    props: ['tableDatas', 'columns','disabled'],
    setup(props) {
        const state = reactive({
        })
        function exportExcel() {
            let head = {}
            props.columns.forEach(item => {
                if (item.show) {
                    head[item.prop] = item.label
                }
            })
            const list = props.tableDatas.map(item => {
                const obj = {}
                for (const k in item) {
                    if (head[k]) {
                        obj[head[k]] = item[k]
                    }
                }
                return obj
            })
            // 创建工作表
            const data = XLSX.utils.json_to_sheet(list, { header: props.columns.map(item=>item.label) })
            // 创建工作簿
            const wb = XLSX.utils.book_new()
            let cols = []
            let rows = [{ hpx: 20 }]
            for (let index = 0; index < list.length; index++) {
                cols.push({ wch: 30 })
            }
            for (let index = 0; index < props.tableDatas.length; index++) {
                rows.push({ hpx: 20 })
            }
            data["!cols"] = cols
            data["!rows"] = rows

            // 将工作表放入工作簿中
            XLSX.utils.book_append_sheet(wb, data, 'data')
            // 生成文件并下载
            XLSX.writeFile(wb, '列表导出文件.xlsx')
        }

        return {
            ...toRefs(state), exportExcel,props,
        }
    }
}
</script>

